<template>
  <basic-container page-title="分组管理" custom-content>
    <template #filter>
      <GroupFilterBar
        v-model="filterBarState"
        :loading="loading"
        :is-select="!!selectedRows?.length"
        @create="openEditGroupDialog()"
        @search="handleSearch()"
        @batch-delete="handleBatchDelete"
        @refresh="getList()"
      />
    </template>

    <el-table
      ref="tableRef"
      v-loading="loading"
      :data="tableData"
      class="basic-table"
      :tooltip-options="{ popperClass: 'basic-tooltip' }"
      height="100%"
      @selection-change="handleTableSelectionChange"
    >
      <template #empty><TableEmpty /></template>
      <!-- <el-table-column type="selection" width="55"></el-table-column> -->
      <el-table-column
        label="分组名称"
        min-width="150"
        show-overflow-tooltip
        prop="name"
        :formatter="emptyFormatter"
      />
      <el-table-column label="关联用户数" min-width="150">
        <template #default="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="toUserListPage(row.id)"
          >
            <span v-format-number="row.user_num"></span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="200" prop="remark">
        <template #default="{ row }">
          <basic-edit-table-remark
            :content="row.remark"
            :submit="value => handleEditRemark(row, value)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="actions" fixed="right" label="操作" width="110">
        <template #default="{ row }">
          <div class="flex items-center gap-x-4">
            <el-link
              class="font-normal"
              type="primary"
              :underline="false"
              @click="openEditGroupDialog(row)"
            >
              编辑
            </el-link>
            <el-link
              class="font-normal"
              type="danger"
              :underline="false"
              @click="handleDelete(row)"
            >
              删除
            </el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <basic-pagination
        ref="paginationRef"
        :table-ref="tableRef"
        :pagination="pagination"
        :batch-button-props="{
          disabled: selectedRows?.length === 0
        }"
        :batch-click="handleBatchDelete"
        @change="getList()"
      ></basic-pagination>
    </template>
  </basic-container>

  <edit-group-dialog
    v-model:visible="editGroup.visible"
    v-model:loading="editGroup.loading"
    :record="editGroup.record"
    @reload="getList()"
  ></edit-group-dialog>
  <CommonDealDialog
    v-model:visible="dealDialog.visible"
    :record="dealDialog.record"
    :command="dealDialog.command"
    :content="dealDialog.content"
    @reload="getList"
  ></CommonDealDialog>
</template>

<script setup lang="ts">
import type { TableInstance } from 'element-plus'

import type { UserGroupModel } from '@/apis/model/user'
import { BasicContainer, CommonDealDialog } from '@/components/application'
import { useFilterBarState } from '@/hooks/useFilterBarState'
import { useListRequest } from '@/hooks/useListRequest'
import useTableSelection from '@/hooks/useTableSelection'
import ToastUtils from '@/utils/toast'

import GroupFilterBar from './components/GroupFilterBar.vue'
import EditGroupDialog from './dialogs/EditGroupDialog.vue'

const router = useRouter()

const tableRef = ref<TableInstance>()
const paginationRef = ref()

const formState = reactive({})

const { filterBarState, queryState } = useFilterBarState(formState)

/**
 * 列表数据，数据的首次获取由filter-bar组件触发
 */
const {
  data: tableData,
  getList,
  pagination,
  loading
} = useListRequest(userGroupListApi, queryState)

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.page = 1
  getList()
}

/**
 * 列表选择
 */
const { selectedRows, handleTableSelectionChange } = useTableSelection(
  tableData,
  paginationRef
)

/**
 * 新建/编辑分组dialog
 */
const editGroup = reactive<CommonDialog<UserGroupModel>>({
  visible: false,
  record: null,
  loading: false
})
const openEditGroupDialog = (group?: UserGroupModel) => {
  editGroup.record = group
  editGroup.visible = true
}

/**
 * 带上用户组ID到用户列表页面筛选
 * @param groupId 用户组ID
 */
const toUserListPage = (groupId: string) => {
  router.push({ name: 'UserList', params: { groupId } })
}

const { setMessageBox } = useMessageBox()
/**
 * 删除分组
 */
const handleDelete = (group: UserGroupModel) => {
  setMessageBox({
    content: '删除后不可恢复，是否确定删除',
    title: '确定删除？',
    async submit() {
      try {
        await deleteUserGroupApi({ id: group.id! })
        ToastUtils.success('删除成功')
        decPageByData(pagination, tableData)
        getList()

        setMessageBox({ visible: false })
      } finally {
        setMessageBox({ loading: false })
      }
    }
  })
}

const handleEditRemark = async (row: UserGroupModel, remark: string) => {
  await putUserGroupApi({ id: row.id!, remark })
  getList()
  ToastUtils.success('修改成功')
}

/**
 * 批量删除用户分组
 */
const dealDialog = reactive<CommonDialog>({
  visible: false,
  loading: false,
  record: undefined,
  command: '',
  content: ''
})
const handleBatchDelete = () => {
  const ids = selectedRows.value?.map(item => item.id)
  dealDialog.visible = true
  dealDialog.record = ids
  dealDialog.command = 'batchDeleteUserGroup'
  dealDialog.content = '删除后不可恢复，是否确定删除？'
}

onMounted(getList)
</script>

<style scoped lang="scss"></style>
